<template>
  <div class="link-share-con" v-loading="loading">
    <div class="header flex items-center justify-center">
      <div class="left-avator mr-3">
        <SvgIcon icon="tongyong_MDwenjian" size="80px"></SvgIcon>
      </div>
      <div class="share-info">
        <div class="title flex items-center">
          <h3 class="text-primaryColor mr-2">外链分享</h3>
          <n-tag :bordered="false" type="info"> {{ shareInfo.title }}</n-tag>
        </div>
        <div class="path text-[13px] mt-2 text-[#aaa]">
          <span class="font-bold">所在位置：</span>
          <span>{{ shareInfo.path }}</span>
        </div>
        <div class="desc text-[13px] mt-2 text-[#aaa]">
          <span class="font-bold">分享时间：</span>
          <span class="text-gray">{{ shareInfo.createTime }}</span>
          <span class="font-bold">，浏览数：</span>
          <span>{{ shareInfo.numView }}</span>
          <span class="font-bold">，下载数：</span>
          <span>{{ shareInfo.numDownload }}</span>
        </div>
      </div>
    </div>
    <n-divider class="!my-2" />
    <n-form
      class="p-2"
      ref="formRef"
      :label-width="200"
      :label-placement="menuShow ? 'left' : 'top'"
      label-align="right"
      :model="shareInfo"
      size="small"
      require-mark-placement="left"
      :rules="formRule"
    >
      <n-form-item label="分享链接：" path="shareUrl">
        <n-input-group class="!w-[300px]">
          <n-input
            :value="shareInfo.url"
            :allow-input="noSideSpace"
            :maxlength="255"
            clearable
            :disabled="true"
          />

          <n-tooltip trigger="hover">
            <template #trigger>
              <n-button type="default" @click="handleOpenLink">
                <SvgIcon icon="zhuanfa1"></SvgIcon>
              </n-button>
            </template>
            打开链接
          </n-tooltip>
        </n-input-group>
      </n-form-item>
      <n-form-item label="提取密码：" path="code">
        <n-input
          class="!w-[300px]"
          v-model:value="shareInfo.code"
          placeholder="请输入提取密码,为空则不设置密码"
          :allow-input="noSideSpace"
          clearable
          :maxlength="20"
        />
      </n-form-item>

      <n-form-item label="更多：">
        <n-radio-group v-model:value="shareInfoType" name="radiobuttongroup2">
          <n-radio-button :value="0">
            <SvgIcon
              icon="shezhi-shezhi-tianchong"
              :color="shareInfoType === 0 ? '#fff' : '#999'"
              class="mr-1"
            ></SvgIcon>
            基础设置
          </n-radio-button>
          <n-radio-button :value="1">
            <SvgIcon
              icon="gengduo"
              :color="shareInfoType === 1 ? '#fff' : '#999'"
            ></SvgIcon>
            更多设置
          </n-radio-button>
        </n-radio-group>
      </n-form-item>

      <my-transition>
        <div v-if="shareInfoType === 1">
          <n-form-item label="分享标题：" path="title">
            <n-input
              class="!w-[300px]"
              v-model:value="shareInfo.title"
              placeholder="请输入分享标题"
              :allow-input="noSideSpace"
              clearable
            />
          </n-form-item>
          <n-form-item label="仅登录用户可用：" path="options.forbidNotLogin">
            <n-switch
              :value="shareInfo.options.forbidNotLogin === '1'"
              @update:value="
                (value: boolean) =>
                  (shareInfo.options.forbidNotLogin = '' + +value)
              "
            />
            <div class="ml-[12px] text-gray-400 text-[12px]">
              开启后仅内部人员可访问
            </div>
          </n-form-item>
          <n-form-item label="到期时间：" path="openDeadLine">
            <n-switch
              :value="shareInfo.openDeadLine === '1'"
              @update:value="
                (value: boolean) => (shareInfo.openDeadLine = '' + +value)
              "
            />
            <div class="ml-[12px] text-gray-400 text-[12px]">
              开启并设置后，超过时间分享自动失效
            </div>
          </n-form-item>

          <my-transition>
            <div v-if="shareInfo.openDeadLine === '1'">
              <n-form-item path="deadline" label=" ">
                <n-date-picker
                  v-model:value="shareInfo.deadline"
                  type="datetime"
                  clearable
                />
              </n-form-item>
            </div>
          </my-transition>

          <n-divider class="!my-2" />
          <n-form-item label="权限及限制：">
            <n-checkbox
              :checked="shareInfo.options.forbidView === '1'"
              @update:checked="
                (value: boolean) => (shareInfo.options.forbidView = '' + +value)
              "
            >
              禁用预览
            </n-checkbox>
            <n-checkbox
              :checked="shareInfo.options.forbidDownload === '1'"
              @update:checked="
                (value: boolean) =>
                  (shareInfo.options.forbidDownload = '' + +value)
              "
            >
              禁用下载
            </n-checkbox>
            <n-checkbox
              :checked="shareInfo.isLimitDownloadCnt === '1'"
              @update:checked="
                (value: boolean) => (shareInfo.isLimitDownloadCnt = '' + +value)
              "
            >
              下载次数
            </n-checkbox>
          </n-form-item>

          <my-transition>
            <div v-if="shareInfo.isLimitDownloadCnt === '1'">
              <n-form-item
                label="下载次数限制："
                path="options.downloadLimitCnt"
              >
                <n-input-number
                  v-model:value="shareInfo.options.downloadLimitCnt"
                  placeholder="请输入下载最大次数"
                  clearable
                  :min="1"
                  :max="1e131"
                />
                <div class="ml-[12px] text-gray-400 text-[12px]">
                  超过该次数，分享链接自动失效
                </div>
              </n-form-item>
            </div>
          </my-transition>
        </div>
      </my-transition>
    </n-form>

    <n-divider class="!my-2" />
    <div class="footer flex justify-end items-center">
      <n-button type="tertiary" @click="handleToCancelShare">取消分享</n-button>
      <n-button
        class="mx-2 grent-btn"
        type="primary"
        @click="handleToUpdateShare"
      >
        复制&保存
      </n-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useMessage, useDialog } from 'naive-ui'
import userUserStore from '@/stores/modules/user'
import { cancelShare, createShare, updateShare } from '@/api/share'
import { getSourceById } from '@/api/source'
import { BASE_URL } from '@/constants'
import { userMenuShow } from '@/hooks/useMenuShow'
import { formatTime, noSideSpace } from '@/utils'
import { load } from '@/utils/loading'

const message = useMessage()
const router = useRouter()
const dialog = useDialog()
const userStore = userUserStore()
const props = defineProps<{
  sourceId: string
}>()

const emits = defineEmits<{
  (e: 'close'): void
}>()

const { menuShow } = userMenuShow()

const shareInfoType = ref(0)

const shareInfo = reactive({
  id: '',
  url: '',
  code: '',
  title: '',
  openDeadLine: '0',
  deadline: Date.now(),
  isLimitDownloadCnt: '0',
  options: {
    forbidNotLogin: '0',
    forbidView: '0',
    forbidDownload: '0',
    downloadLimitCnt: '0'
  },
  numView: 0,
  numDownload: 0,
  createTime: '',
  path: ''
})

const formRule = {
  code: [
    {
      pattern: /^[a-zA-Z0-9]{4,20}$/,
      message: '提取码由数字和字母组成，4-20位',
      trigger: ['blur']
    }
  ]
}

const loading = ref(false)

const getLabelName = (id: string, label: string) => {
  if (id === userStore.userInfo?.rootSourceId) {
    return '个人空间'
  }
  return label
}

// 根据ID查询文件详情
const loadSourceInfo = () => {
  loading.value = true
  getSourceById({ sourceId: props.sourceId })
    .then((res) => {
      if (!res.data) {
        return message.warning('资源ID有误')
      }
      if (!res.data.Share) {
        // 创建一个share
        shareInfo.title = res.data.filename
        createShare({
          title: res.data.filename,
          sourceId: res.data.id
        }).then(() => {
          loadSourceInfo()
        })
      } else {
        // 进行值的更新
        const {
          title,
          id,
          deadline,
          options,
          code,
          numView,
          numDownload,
          createTime
        } = res.data.Share
        shareInfo.url = BASE_URL + '/' + id
        shareInfo.title = title
        shareInfo.deadline = +deadline === 0 ? Date.now() : +deadline
        shareInfo.openDeadLine = +deadline === 0 ? '0' : '1'
        shareInfo.options = JSON.parse(options)
        shareInfo.code = code
        shareInfo.isLimitDownloadCnt =
          +shareInfo.options.downloadLimitCnt === 0 ? '0' : '1'
        shareInfo.numView = numView
        shareInfo.numDownload = numDownload
        shareInfo.createTime = formatTime(createTime)
        shareInfo.path = res.data.pathInfo
          .map((item) => getLabelName(item.id, item.filename))
          .join('/')
        shareInfo.id = id
      }
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  loadSourceInfo()
})

// 更新share
const handleToUpdateShare = () => {
  load.show()
  updateShare({
    shareId: shareInfo.id,
    code: shareInfo.code,
    title: shareInfo.title,
    isLink: 1,
    deadline:
      shareInfo.openDeadLine === '1' ? '' + shareInfo.deadline : undefined,
    options: shareInfo.options
  })
    .then(() => {
      message.success('操作成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

// 取消分享share
const handleToCancelShare = () => {
  dialog.warning({
    title: '提示',
    content: '你确定要取消该分享吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      load.show()
      cancelShare({
        shareIds: [shareInfo.id],
        type: 0
      })
        .then(() => {
          message.success('操作成功')
          afterOpt()
        })
        .catch(console.error)
        .finally(() => {
          load.hide()
        })
    },
    onNegativeClick: () => {}
  })
}

// 跳转到分享详情
const handleOpenLink = () => {
  const route = router.resolve({
    name: 'linkShare',
    query: {
      shareId: shareInfo.id
    }
  })

  // 打开新tab页
  window.open(route.href, '_blank')
}

const afterOpt = () => {
  emits('close')
}
</script>

<style scoped lang="scss">
.link-share-con {
  .header {
    height: 120px;

    background-image: -webkit-linear-gradient(bottom, #fdfeff, #daf3ff);
  }

  .footer {
    height: 56px;
    background-color: #fcfcfc;
  }
}
</style>
